package com.lcy.smartcity.service;

import com.lcy.smartcity.entity.User;
import com.lcy.smartcity.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;


@Service
public class UserService {

    @Autowired
    private UserMapper userMapper;

    public List<User> getAllUsers() {
        return userMapper.findAll();
    }
    public User findByUsername(String username) {
        return userMapper.findByUsername(username);
    }

    public User findByPhoneNumber(String phoneNumber) {
        return userMapper.findByPhoneNumber(phoneNumber);
    }
    public User findById(Long id) {
        return userMapper.findById(id);
    }

    public Boolean register(String username, String password, String phoneNumber) {
        // 检测用户名是否已存在
        if (userMapper.findByUsername(username) != null) {
            return false;   // 用户名已存在
        }

        // 检测手机号是否已注册过
        if (userMapper.findByPhoneNumber(phoneNumber) != null) {
            return false;   // 手机号已注册过
        }

        // 创建新用户
        User user = new User(username, password, phoneNumber);
        userMapper.register(user);
        return true;
    }

    public User login(String phoneNumber, String password) {
        User user = userMapper.findByPhoneNumber(phoneNumber);
        if (user != null && user.getPassword().equals(password)) {
            return user;
        }
        return null;
    }
    public boolean updatePassword(String phoneNumber, String oldPassword, String newPassword) {
        User user = userMapper.findByPhoneNumber(phoneNumber);
        if (user != null && user.getPassword().equals(oldPassword)) {
            user.setPassword(newPassword);
            user.setUpdatedAt(LocalDateTime.now());
            userMapper.updatePassword(user);
            return true;
        }
        return false;
    }

    public boolean updateAdminStatus(Long userId, Boolean isAdmin, Long currentUserId) {
        // 检查当前用户是否为超级管理员
        User currentUser = userMapper.findById(currentUserId);
        if (currentUser == null || !currentUser.getIsSuperAdmin()) {
            return false; // 当前用户不是管理员
        }

        // 更新用户权限
        User user = userMapper.findById(userId);
        if (user == null) {
            return false; // 用户不存在
        }

        user.setIsAdmin(isAdmin);
        user.setUpdatedAt(LocalDateTime.now());
        userMapper.updateAdminStatus(user);
        return true;
    }
}
